package main

import (
	"context"
	"fmt"
	"github.com/mongodb/mongo-go-driver/bson/objectid"
	"github.com/mongodb/mongo-go-driver/mongo"
	"github.com/mongodb/mongo-go-driver/options"
	"time"
)

type TimePoint struct {
	StartTime int64 `bson:"startTime"`
	EndTime   int64 `bson:"endTime"`
}

type CronJob struct {
	JobName   string    `bson:"jobName"`
	Command   string    `bson:"command"`
	Err       string    `bson:"err"`
	Content   string    `bson:"content"`
	TimePoint TimePoint `bson:"timePoint"`
}

type FindByJobName struct {
	JobName string `bson:"jobName"`
}

type TimeBeforeCondition struct {
	Before int64 `bson:"$lt"`
}

type DeleteCondition struct {
	BeforeCondition TimeBeforeCondition `bson:"timePoint.startTime"`
}

func main() {
	client, err := mongo.Connect(context.TODO(), "mongodb://127.0.0.1:27017")
	if err != nil {
		fmt.Println(err)
		return
	}

	DeleteMany(client)
}

func DeleteMany(client *mongo.Client) {
	condition := &DeleteCondition{
		BeforeCondition: TimeBeforeCondition{
			Before: time.Now().Unix(),
		},
	}

	collection := client.Database("cron").Collection("log")

	result, err := collection.DeleteMany(context.TODO(), condition)
	if err != nil {
		fmt.Println(err)
	}

	fmt.Println(result.DeletedCount)
}

func FindOne(client *mongo.Client) {
	findByJobName := &FindByJobName{
		JobName: "job2",
	}

	limit := int64(2)
	skip := int64(0)
	collection := client.Database("cron").Collection("log")
	findOptions := &options.FindOptions{
		Limit: &limit,
		Skip:  &skip,
	}
	cursor, err := collection.Find(context.TODO(), findByJobName, findOptions)
	defer cursor.Close(context.TODO())
	fmt.Println(err)

	for cursor.Next(context.Background()) {
		result := &CronJob{}

		err := cursor.Decode(&result)
		if err != nil {
			fmt.Println(err)
		}
		fmt.Println(result)
	}
}

func InsertOne(client *mongo.Client) {
	collection := client.Database("cron").Collection("log")
	cronJob := &CronJob{
		JobName: "job2",
		Command: "echo hello",
		Err:     "",
		Content: "hello",
		TimePoint: TimePoint{
			StartTime: time.Now().Unix(),
			EndTime:   time.Now().Unix(),
		},
	}

	result, err := collection.InsertOne(context.TODO(), cronJob)
	ids := result.InsertedID.(objectid.ObjectID)
	fmt.Println(ids.Hex(), err)
}
